package com.fy56.platform.logistics.restful.api.controller.wx;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.common.ResultStatus;
import com.fy56.platform.logistics.model.*;
import com.fy56.platform.logistics.restful.api.app.authorization.annotation.Authorization;
import com.fy56.platform.logistics.service.web.IMiniProgramService;
import com.fy56.platform.logistics.service.wx.*;
import com.fy56.platform.logistics.utils.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by lml on 2018/2/26.
 */
@Api(value = "Order", description = "订单", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/order")
public class OrderController {
    private static Logger log = Logger.getLogger(OrderController.class);
    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private WithdrawMoneyService withdrawMoneyService;
    @Autowired
    private ICompanyInfoService iCompanyInfoService;
    @Autowired
    private IPayOrderService iPayOrderService;
    @Autowired
    private IMiniProgramService iMiniProgramService;
    @Autowired
    private IVipService iVipService;

    /**
     * 去重
     *
     * @param list
     */
    private static List<Map<String, Object>> getWithOutDuplicateList(List<Map<String, Object>> list) {
        List<Map<String, Object>> result = Lists.newArrayList();
        result.addAll(list);
        for (int i = 0; i < result.size() - 1; i++) {
            for (int j = result.size() - 1; j > i; j--) {
                if (result.get(j).get("vipNo").toString().equals(result.get(i).get("vipNo").toString())) {
                    result.remove(j);
                }
            }
        }
        return result;
    }

    @RequestMapping(value = "/saveOrder", method = RequestMethod.POST)
    @ApiOperation(value = "保存订单")
    @Authorization
    public ResponseEntity saveOrder(@RequestParam String data) {
        long startTime = System.currentTimeMillis();
        Order order = null;
        Integer result = 0;
        try {
            if (data != null && data.length() != 0) {
                order = JSON.parseObject(data, Order.class);
                order.setGenerateFlag(false);
                order.setOrderCreateTime(new Date());
                order.setId(Long.parseLong(IdWorkerTools.getInstance().getId()));
                //生成提货码
                order.setPickUpCode(generatePickupCode(order.getSenderMobile(),order.getTenantCode()));
                //设置来源：小程序
                order.setResource(1);
                //初始化金额字段（不能为空）
                if (order.getCollectionOfMoney() == null) {
                    order.setCollectionOfMoney(0.0);
                }
                if (order.getFreight() == null) {
                    order.setFreight(0.0);
                }
                if (order.getCashOnDelivery() == null) {
                    order.setCashOnDelivery(0.0);
                }
                if (order.getWeight() == null) {
                    order.setWeight(0.0);
                }
                if (order.getBulk() == null) {
                    order.setBulk(0.0);
                }
                result = iOrderService.save(order);


                try {
                    Vip vip = new Vip();
                    vip.setMobile(order.getMobile());
                    vip.setDefaultPlaceOfLoading(order.getPlaceOfLoading());
                    iVipService.updateDefaultPlaceOfLoading(vip);
                    VipAppId vipAppId = new VipAppId();
                    vipAppId.setDefaultPlaceOfLoading(order.getPlaceOfLoading());
                    vipAppId.setCode(order.getTenantCode());
                    vipAppId.setVipMemberId(Long.valueOf(order.getUserId()));
                    iVipService.updateVipAppId(vipAppId);
                } catch (Exception e) {
                    log.error("更新默认寄件网点失败", e);
                }
            }
        } catch (Exception e) {
            log.error("保存订单失败", e);
        } finally {
            if (result > 0) {
                ResultModel resultModel = ResultModel.ok();
                //推送业务系统订单消息
                long s = System.currentTimeMillis();
                log.info("推送业务系统订单消息开始：" + s);
                order.setOrderNumber(String.valueOf(order.getId()));
                if (order.getOpenId() != null && order.getOpenId().length() != 0) {
                    order.setUserId(order.getOpenId());
                }
//                order.setUserId(order.getOpenId());
                sendMessageToBusiness(order);
                log.info("推送业务系统订单消息结束：用时" + (System.currentTimeMillis() - s));

                //同步业务系统数据
                long start = System.currentTimeMillis();
                log.info("同步业务保存订单系统数据开始：" + start);
                String resultF6Order = syncPreOrder(order, "add");
                if ("SUCCESS".equals(resultF6Order)) {
                    order.setUploadFlag("1");
                    order.setUploadTime(new Date());
                    iOrderService.updateUploadFlag(order);//updateUploadFlag
                }

                log.info(resultF6Order);
                log.info("同步业务保存订单系统数据结束：用时" + (System.currentTimeMillis() - start));
                long endTime = System.currentTimeMillis();
                log.info("保存订单总用时" + (endTime - startTime));

                // 判断运费大于0时，生成微信支付统一下单信息
                if (order.getFreight() > 0) {
                    ResultModel subResultModel = savePayOrder(order.getTenantCode(), order.getOpenid(), order.getMobile(), order.getId() + "", order.getFreight(), "运费", "");
                    resultModel.setSubResultModel(subResultModel);
                }
                return new ResponseEntity<>(resultModel, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(ResultModel.error(ResultStatus.INSERT_ERR), HttpStatus.CREATED);
            }
        }
    }

    /**
     * 保存微信支付统一下单
     *
     * @param code          租户金融代码
     * @param openId        微信用户openId
     * @param mobile        用户手机号码
     * @param orderNo       订单ID
     * @param money         运费金额
     * @param goodsDescribe 运费
     * @param remark        支付订单备注
     * @return
     */
    public ResultModel savePayOrder(String code, String openId, String mobile, String orderNo, Double money, String goodsDescribe, String remark) {
        ResultModel result = null;
        try {
            PayOrder payOrder = new PayOrder();
            String paramErrorMsg = "";
            // 1 验证openID
            if (StringUtil.isNotEmpty(openId)) {
                payOrder.setOpenId(openId);
            } else {
                paramErrorMsg += "openId参数有误 ";
            }
            // 2 验证 code
            if (StringUtil.isNotEmpty(code)) {
                // 2.1 获取code对应关联的小程序设置信息
                MiniProgram miniProgram = iMiniProgramService.selectByCode(code);
                if (miniProgram != null && StringUtil.isNotEmpty(miniProgram.getTradingcenterUrl()) && StringUtil.isNotEmpty(miniProgram.getTradingcenterMchKey())) {
                    payOrder.setAppId(miniProgram.getAppid());
                    payOrder.setMiniProgram(miniProgram);
                } else {
                    paramErrorMsg += code + ":code对应小程序与支付信息未设置 ";
                }
                // 2.2 获取code 对应关联的company信息
                Company company = iCompanyInfoService.getCompanyByCode(code);
                if (company != null) {
                    payOrder.setCompany(company);
                } else {
                    paramErrorMsg += code + ":code无对应公司信息 ";
                }
                payOrder.setCode(code);
            } else {
                paramErrorMsg += code + ":code参数有误 ";
            }
            // 3 mobile
            if (StringUtil.isNotEmpty(mobile)) {
                Vip vipMember = iVipService.selectVipOpenidByMobile(mobile);
                if (vipMember != null) {
                    payOrder.setVipMemberId(vipMember.getId().toString());
                    payOrder.setMobile(vipMember.getMobile());
                    payOrder.setVip(vipMember);
                } else {
                    paramErrorMsg += (mobile + ",用户不存在 ");
                }
                payOrder.setMobile(mobile);
            } else {
                paramErrorMsg += "mobile参数有误 ";
            }
            // 4 orderNo
            if (StringUtil.isNotEmpty(orderNo)) {
                String payOrderNo = iPayOrderService.getPayOrderNotByParamsService(orderNo);
                if (StringUtil.isNotEmpty(payOrderNo)) {
                    if (payOrderNo.indexOf("YUNFEI") > -1) {
                        payOrder.setGeneratorOrderType("YUNFEI");
                    }
                    if (payOrderNo.indexOf("CHAJIA") > -1) {
                        payOrder.setGeneratorOrderType("CHAJIA");
                    }
                    payOrder.setOrderNo(payOrderNo);
                } else {
                    paramErrorMsg += orderNo + "支付订单号已存在 ";
                }
            } else {
                paramErrorMsg += "orderNo支付订单编号有误 ";
            }
            payOrder.setMoney(money);
            payOrder.setGoodsDescribe(goodsDescribe);
            payOrder.setRemark(remark);
            //2 调用统一下单ServiceImp发功能
            if (StringUtil.isEmpty(paramErrorMsg)) {
                result = iPayOrderService.insertSelective(payOrder);
            } else {
                result = new ResultModel(101, paramErrorMsg, null);
            }
        } catch (Exception ex) {
            log.error("OrderController支付订单-savePayOrder，下单savePayOrder功能异常：", ex);
            result = new ResultModel(101, "支付订单下单savePayOrder功能异常。", null);
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * 关闭微信待支付订单
     *
     * @param code
     * @param payOrder
     * @return
     */
    public ResultModel closePayOrder(String code, PayOrder payOrder) {
        ResultModel result = null;
        try {
            String paramErrorMsg = "";
            // 2 验证 code
            if (StringUtil.isNotEmpty(code)) {
                // 2.1 获取code对应关联的小程序设置信息
                MiniProgram miniProgram = iMiniProgramService.selectByCode(code);
                if (miniProgram != null && StringUtil.isNotEmpty(miniProgram.getTradingcenterUrl()) && StringUtil.isNotEmpty(miniProgram.getTradingcenterMchKey())) {
                    payOrder.setAppId(miniProgram.getAppid());
                    payOrder.setMiniProgram(miniProgram);
                } else {
                    paramErrorMsg += code + ":code对应小程序与支付信息未设置 ";
                }
                // 2.2 获取code 对应关联的company信息
                Company company = iCompanyInfoService.getCompanyByCode(code);
                if (company != null) {
                    payOrder.setCompany(company);
                } else {
                    paramErrorMsg += code + ":code无对应公司信息 ";
                }
                payOrder.setCode(code);
            } else {
                paramErrorMsg += code + ":code参数有误 ";
            }

            // 2 查询统一下单 根据单号
            if (StringUtil.isEmpty(paramErrorMsg)) {
                result = iPayOrderService.updateClosePayOrder(payOrder);
            } else {
                result = new ResultModel(101, paramErrorMsg, null);
            }
        } catch (Exception ex) {
            log.error("OrderController支付订单-closePayOrder，根据交易单号关闭订单功能异常：", ex);
            result = new ResultModel(101, "根据交易单号关闭订单功能异常", null);
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * 使用手机号后5位作为提货码
     *
     * @param mobile
     * @return
     */
    private String generatePickupCode(String mobile, String tenantCode) {
        //云南永越下单码改成手机号后六位。只有一家
        if("M4767".equals(tenantCode)){
            return StringUtil.isEmpty(mobile) ? null : mobile.substring(mobile.length() - 6);
        }else{
            return StringUtil.isEmpty(mobile) ? null : mobile.substring(mobile.length() - 5);
        }

    }

    @RequestMapping(value = "/editOrder", method = RequestMethod.POST)
    @ApiOperation(value = "修改订单")
    @Authorization
    public ResponseEntity editOrder(@RequestParam String data) {
        long startTime = System.currentTimeMillis();
        Order order = null;
        Integer result = 0;
        String errorMessage = "";
        try {
            if (data != null && data.length() != 0) {
                order = JSON.parseObject(data, Order.class);
                //生成提货码
                order.setPickUpCode(generatePickupCode(order.getSenderMobile(),order.getTenantCode()));
                //初始化金额字段（不能为空）
                if (order.getCollectionOfMoney() == null) {
                    order.setCollectionOfMoney(0.0);
                }
                if (order.getFreight() == null) {
                    order.setFreight(0.0);
                }
                if (order.getCashOnDelivery() == null) {
                    order.setCashOnDelivery(0.0);
                }
                if (order.getWeight() == null) {
                    order.setWeight(0.0);
                }
                if (order.getBulk() == null) {
                    order.setBulk(0.0);
                }
                Order oldOrder = iOrderService.selectByPrimaryKey(order.getId());
                if (oldOrder != null && oldOrder.getGenerateFlag()) {
                    errorMessage = "修改失败,已转成正式订单";
                } else {
                    result = iOrderService.updateById(order);
                }
            }
        } catch (Exception e) {
            log.error("修改订单失败", e);
        } finally {
            if (result > 0) {
                ResultModel resultModel = ResultModel.ok();

                //同步业务系统数据
                long start = System.currentTimeMillis();
                log.info("同步业务修改订单系统数据开始：" + start);
                order.setOrderNumber(String.valueOf(order.getId()));
                log.info(syncPreOrder(order, "edit"));
                log.info("同步业务修改订单系统数据结束：用时" + (System.currentTimeMillis() - start));
                long endTime = System.currentTimeMillis();
                log.info("保存订单总用时" + (endTime - startTime));


                ResultModel closePayOrderModel = ResultModel.ok();
                // 1 查询该订单的-微信支付订单信息[未付款且未关闭]的 , 循环关闭支付订单
                List<PayOrder> payOrders = iPayOrderService.findPayOrderByParamsService(order.getId().toString());
                if (payOrders != null && payOrders.size() > 0) {
                    for (PayOrder payOrder : payOrders) {
                        closePayOrderModel = closePayOrder(order.getTenantCode(), payOrder);
                    }
                }
                // 2 判断运费大于0时，关闭原来支付的统一下单，新生产支付订单
                if (order.getFreight() > 0) {
                    // 判断若原订单关闭成功，则添加新待支付订单
                    if (closePayOrderModel.getCode() == 100) {
                        ResultModel subResultModel = savePayOrder(order.getTenantCode(), order.getOpenid(), order.getSenderMobile(), order.getId() + "", order.getFreight(), "运费", "");
                        resultModel.setSubResultModel(subResultModel);
                    } else {
                        resultModel.setSubResultModel(closePayOrderModel);
                    }
                }
                return new ResponseEntity<>(resultModel, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(ResultModel.error(ResultStatus.EDIT_ERR), HttpStatus.CREATED);
            }
        }
    }

    /**
     * 同步预受理单至BS和F6服务
     *
     * @param order
     */
    private String syncPreOrder(Order order, String operate) {

        String resultR = "";
        //如果是F6系统，则不同步数据
        Company company = iCompanyInfoService.getCompanyByCode(order.getTenantCode());
        if (company == null || StringUtil.isEmpty(company.getUrl())) {
            throw new NullPointerException("未设置租户信息");
        }
        //初始化请求参数
        Map<String, String> postParams = Maps.newHashMap();

        //BS同步数据地址
        String url = company.getUrl() + "/preAcceptOrder/syncPreOrder";

        //F6同步数据地址
        if (StringUtil.isNotEmpty(company.getF6AccountSet()) && StringUtil.isNotEmpty(company.getF6OrganizationCode())) {
            url = company.getUrl() + "/orderBill/" + operate + "?databaseId=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
        }
        postParams.put("data", JSONObject.toJSONString(order, SerializerFeature.WriteMapNullValue));
        log.info("syncPreOrder:url"+url+"   "+JSONObject.toJSONString(postParams));
        System.out.println("syncPreOrder:url"+url+"   "+JSONObject.toJSONString(postParams));
        String result = HttpAsyncUtil.asyncPost(url, postParams, HttpUtil.setHeader());
        log.info("syncPreOrder:result"+result);
        if (StringUtil.isNotEmpty(result)) {
            ResultModel model = JSON.parseObject(result, ResultModel.class);
            if (200 == model.getCode()) {
                if ("SUCCESS".equals(model.getMsg())) {
                    resultR = "SUCCESS";
                    log.info("同步业务系统数据成功");
                } else {
                    log.info("同步业务系统数据失败，原因：" + model.getMsg());
                }
            } else {
                log.info("同步业务系统数据失败，原因：请求BS，F6服务端出错！");
            }
        }
        return resultR;
    }

    /**
     * 推送业务系统订单消息
     *
     * @param order
     */
    private boolean sendMessageToBusiness(Order order) {

        boolean resultR = false;
        //如果是F6系统，则不同步数据
        Company company = iCompanyInfoService.getCompanyByCode(order.getTenantCode());
        if (company == null || StringUtil.isEmpty(company.getUrl())) {
            log.info("推送业务系统订单消息失败，原因：未设置租户信息！");
            return resultR;
        }

        //执行推送
        if (StringUtil.isNotEmpty(company.getF6AccountSet()) && StringUtil.isNotEmpty(company.getF6OrganizationCode())) {

            //拼接post请求地址
            String url = company.getUrl() + "/wechatinfo?databaseId=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();

            //构筑请求参数
            Map<String, String> postParams = Maps.newHashMap();
            postParams.put("data", JSONObject.toJSONString(order, SerializerFeature.WriteMapNullValue));

            //执行推送（异步请求）
            String result = HttpAsyncUtil.asyncPost(url, postParams, HttpUtil.setHeader());
            if (StringUtil.isNotEmpty(result)) {
                ResultModel model = null;
                try {
                    model = JSON.parseObject(result, ResultModel.class);
                    if (200 == model.getCode()) {
                        if ("SUCCESS".equals(model.getMsg())) {
                            resultR = true;
                            log.info("推送业务系统订单消息成功");
                        } else {
                            log.info("推送业务系统订单消息失败，原因：" + model.getMsg());
                        }
                    } else {
                        log.info("推送业务系统订单消息失败，原因：请求BS，F6服务端出错！");
                    }
                } catch (Exception e) {
                    log.error("推送业务系统订单消息失败；URL：" + url + "；参数：" + postParams.toString(), e);
                    resultR = false;
                } finally {
                    model = null;
                }
            }
        }
        return resultR;
    }

    @RequestMapping(value = "/deleteOrder", method = RequestMethod.POST)
    @ApiOperation(value = "删除订单")
    @Authorization
    public ResponseEntity deleteOrder(@RequestParam String data) {
        Order order = null;
        Integer result = 0;
        String errorMessage = "";
        log.info("deleteOrder data" + data);
        try {
            if (data != null && data.length() != 0) {
                order = JSON.parseObject(data, Order.class);
                Order oldOrder = iOrderService.selectByPrimaryKey(order.getId());
                if (oldOrder != null && oldOrder.getGenerateFlag()) {
                    errorMessage = "删除失败,已转成正式订单";
                } else {
                    result = iOrderService.deleteById(order);
                }
            }
        } catch (Exception e) {
            log.error("删除订单失败", e);
        } finally {
            if (result > 0) {

                //---同步业务系统数据开始
                long start = System.currentTimeMillis();
                log.info("同步业务系统数据开始：" + start);
                Company company = iCompanyInfoService.getCompanyByCode(order.getTenantCode());
                if (company == null || StringUtil.isEmpty(company.getUrl())) {
                    throw new NullPointerException("未设置租户信息");
                }

                //BS同步数据地址
                String url = company.getUrl() + "/preAcceptOrder/syncPreOrder";

                //F6同步数据地址
                if (StringUtil.isNotEmpty(company.getF6AccountSet()) && StringUtil.isNotEmpty(company.getF6OrganizationCode())) {
                    url = company.getUrl() + "/orderBill/delete?id=" + order.getId() + "&databaseId=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
                }
                String re = HttpAsyncUtil.asyncPost(url, null, HttpUtil.setHeader());
                if (StringUtil.isNotEmpty(re)) {
                    ResultModel model = JSON.parseObject(re, ResultModel.class);
                    if (200 == model.getCode()) {
                        if ("SUCCESS".equals(model.getMsg())) {
                            log.info("同步业务系统数据成功（删除）");
                        } else {
                            log.info("同步业务系统数据失败（删除），原因：" + model.getMsg());
                        }
                    } else {
                        log.info("同步业务系统数据失败（删除），原因：请求BS，F6服务端出错！");
                    }
                }
                log.info("同步业务系统数据结束：用时" + (System.currentTimeMillis() - start));
                return new ResponseEntity<>(ResultModel.ok(), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(ResultModel.error(ResultStatus.DELETE_ERR), HttpStatus.CREATED);
            }
        }
    }

    @RequestMapping(value = "/getOrderList", method = RequestMethod.GET)
    @ApiOperation(value = "查询订单")
    public ResponseEntity<ResultModel> queryOrderList(@RequestParam String data) {
        //data参数说明：
        // 1.金融代码：code
        // 2.开始日期：startDate
        // 3.结束日期：endDate
        // 4.是否受理：generateFlag
        // 5.用户ID：userId
        // 6.用户ID：手机号
        // 7.当前页数：pageIndex
        // 8.每页显示个数：pageCount
        try {
            //定制版小程序：我的运单查询业务系统的数据
            //return new ResponseEntity(ResultModel.ok(iOrderService.queryOrderList(JSON.parseObject(data))), HttpStatus.OK);
            return new ResponseEntity(ResultModel.ok(iOrderService.getAllOrderListFromBusinessSys(JSON.parseObject(data))), HttpStatus.OK);
        } catch (Exception e) {
            log.error("查询订单失败", e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "查询订单失败"), HttpStatus.OK);
        }
    }

    /**
     * 查询我的订单列表
     * <p>
     * /data参数说明：
     * 1.手机号：mobile
     * 2.收寄状态：srFlag[0：发货，1：收货]
     * 3.开始日期：startDate
     * 4.结束日期：endDate
     * 5.当前页数：pageIndex
     * 6.每页显示个数：pageCount
     *
     * @return
     */
    @RequestMapping(value = "/getOrderListPublic", method = RequestMethod.GET)
    @ApiOperation(value = "查询我的订单列表")
    public ResponseEntity<ResultModel> queryMyOrderList(@RequestParam String data) {
        try {
            // 我的运单查询业务系统的数据[我寄出的，我接收的]
            return new ResponseEntity(ResultModel.ok(iOrderService.getMyAllOrderList(JSON.parseObject(data))), HttpStatus.OK);
        } catch (Exception e) {
            log.error("查询订单失败", e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "查询订单失败"), HttpStatus.OK);
        }
    }

    @RequestMapping(value = "/currentTime", method = RequestMethod.GET)
    @ApiOperation(value = "系统时间")
    public ResponseEntity<ResultModel> getDate() {
        Map<String, Object> systemSettingValues = Maps.newHashMap();
        String list = null;
        try {
            systemSettingValues.put("time", DateUtil.getNowTime("yyyy-MM-dd"));
        } catch (Exception e) {
            log.error("获取系统时间", e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "查询订单失败"), HttpStatus.OK);
        }
        return new ResponseEntity(ResultModel.ok(systemSettingValues), HttpStatus.OK);
    }

    @ApiOperation(value = "获取订单基本信息", notes = "根据金融代码和用户ID获取下单的基本信息（目的地，付款方式，提货方式，货物名称，包装样式，收货人）",
            httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/baseInfo", method = RequestMethod.POST)
    @ResponseBody
    @Authorization
    public ResponseEntity getOrderBaseInfo(
            @ApiParam(value = "金融代码", name = "code", required = true) @RequestParam String code,
            @ApiParam(value = "用户ID", name = "userId", required = true) @RequestParam String userId,
            @ApiParam(value = "纬度", name = "latitude", required = false) @RequestParam String latitude,
            @ApiParam(value = "经度", name = "longitude", required = false) @RequestParam String longitude) {

        Map<String, Object> map = null;
        try {
            map = iOrderService.getOrderBaseInfo(code, Long.valueOf(userId), latitude, longitude, "",null);
        } catch (NullPointerException e) {
            log.error("获取订单基本信息失败", e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, code + "未设置租户信息！"), HttpStatus.OK);
        } catch (Exception e) {
            log.error("获取订单基本信息失败", e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "获取订单基本信息失败"), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResultModel.ok(map), HttpStatus.OK);
    }

    @ApiOperation(value = "根据发货人手机号和金融代码获取一卡通信息", notes = "根据发货人手机号和金融代码获取一卡通信息",
            httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/vipCardInfo", method = RequestMethod.POST)
    @ResponseBody
    @Authorization
    public ResponseEntity getVipCardInfo(
            @ApiParam(value = "金融代码", name = "code", required = true) @RequestParam String code,
            @ApiParam(value = "用户手机号", name = "mobile", required = true) @RequestParam String mobile) {

        ResultModel result = null;
        try {
            result = iOrderService.getVipCardInfo(code, mobile);
        } catch (Exception e) {
            log.error("根据发货人手机号和金融代码获取一卡通信息失败", e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "根据发货人手机号和金融代码获取一卡通信息"), HttpStatus.OK);
        }
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @ApiOperation(value = "根据发货人一卡通号和金融代码获取一卡通信息", notes = "根据发货人手机号和金融代码获取一卡通信息",
            httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/vipCardInfo2", method = RequestMethod.POST)
    @ResponseBody
    @Authorization
    public ResponseEntity getVipCardInfo2(
            @ApiParam(value = "金融代码", name = "code", required = true) @RequestParam String code,
            @ApiParam(value = "一卡通号", name = "vipCardNo", required = true) @RequestParam String vipCardNo) {

        ResultModel result = null;
        try {
            result = iOrderService.getVipCardInfo2(code, vipCardNo);
        } catch (Exception e) {
            log.error("根据发货人手机号和金融代码获取一卡通信息失败", e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "根据发货人手机号和金融代码获取一卡通信息"), HttpStatus.OK);
        }
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @ApiOperation(value = "根据发货人手机号和金融代码获取一卡通信息(我的)", notes = "根据发货人手机号和金融代码获取一卡通信息(我的)",
            httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/userVipCards", method = RequestMethod.POST)
    @ResponseBody
    @Authorization
    public ResponseEntity getUserVipCards(
            @ApiParam(value = "金融代码", name = "code", required = true) @RequestParam String code,
            @ApiParam(value = "用户手机号", name = "mobile", required = true) @RequestParam String mobile) {

        ResultModel result = null;
        try {
            result = iOrderService.getVipCardInfo(code, mobile);
            if (result != null && result.getContent() != null) {
                List<Map<String, Object>> list = (List<Map<String, Object>>) result.getContent();
                if (CollectionUtils.isNotEmpty(list)) {
                    //初始化返回值
                    List<Map<String, Object>> cardList = Lists.newArrayList();
                    //获取去重后的list
                    List<Map<String, Object>> newList = getWithOutDuplicateList(list);
                    for (Map<String, Object> map : newList) {
                        //去重后的一卡通列表
                        Map<String, Object> cardMap = Maps.newHashMap();
                        List<Map<String, Object>> bankList = Lists.newArrayList();
                        for (Map<String, Object> bank : list) {
                            if (map.get("vipNo").toString().equals(bank.get("vipNo").toString())) {
                                bankList.add(bank);
                            }
                        }
                        cardMap.put("list", bankList);
                        cardMap.put("vipNo", map.get("vipNo").toString());
                        cardList.add(cardMap);
                    }
                    result.setContent(cardList);
                }
            }
        } catch (Exception e) {
            log.error("根据发货人手机号和金融代码获取一卡通信息失败", e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "根据发货人手机号和金融代码获取一卡通信息"), HttpStatus.OK);
        }
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/searchOrderForIndex", method = RequestMethod.GET)
    @ApiOperation(value = "小程序主页订单信息")
    public ResponseEntity<ResultModel> searchOrderForIndex(@RequestParam String code, @RequestParam String userId, @RequestParam String mobile) {
        Long begin = System.currentTimeMillis();//开始时间
        List<Order> orderList = null;
        List<WithDrawMoneyMain> withdrawList = null;
        List<Map<String, Object>> maps = Lists.newArrayList();
        Map<String, Object> orderMap = null;
        try {

            //获取最新20订单信息（10条正式订单，10条预受理单）
            orderList = iOrderService.searchOrderForIndex(code, userId, mobile);
            if (orderList != null && orderList.size() > 0) {
                for (Order order : orderList) {
                    orderMap = Maps.newHashMap();
                    orderMap.put("tenantCode", order.getTenantCode());
                    orderMap.put("orderNumber", order.getOrderNumber());
                    orderMap.put("withDrawNo", "");
                    orderMap.put("title", order.getReceiver() + "（" + order.getUnloadPlace() + "）");
                    orderMap.put("companyName", order.getTenantName());
                    if (order.getOrderCreateTime() != null) {
                        orderMap.put("date", DateUtil.turnDateToString(order.getOrderCreateTime(), "yyyy-MM-dd"));
                    } else {
                        orderMap.put("date", order.getCreateDate());
                    }
                    orderMap.put("remark", (order.getGenerateFlag() != null && order.getGenerateFlag()) ? "已受理" : "未受理");
                    orderMap.put("generateFlag", (order.getGenerateFlag() != null && order.getGenerateFlag()) ? "1" : "0");
                    orderMap.put("order", order);
                    maps.add(orderMap);
                }
            }

            //获取最新10条取款信息
            withdrawList = withdrawMoneyService.searchWithDrawForIndex(code, mobile);
            if (withdrawList != null && withdrawList.size() > 0) {
                for (WithDrawMoneyMain model : withdrawList) {
                    orderMap = Maps.newHashMap();
                    orderMap.put("tenantCode", model.getCode());
                    orderMap.put("orderNumber", "");
                    orderMap.put("withDrawNo", model.getWithDrawNo());
                    orderMap.put("title", model.getDeliveryCollection() + "元");
                    orderMap.put("companyName", model.getTenantName());
                    orderMap.put("date", model.getCreateDate());
                    orderMap.put("remark", model.getBankCardNo().substring(model.getBankCardNo().length() - 4));
                    orderMap.put("generateFlag", "2");
                    orderMap.put("order", null);
                    maps.add(orderMap);
                }
            }

            //重新排序并得到最新的10条记录
            if (maps.size() > 0) {
                sort(maps);
                if (maps.size() > 10) {
                    maps = maps.subList(0, 10);
                }
            }
            Long end = System.currentTimeMillis();//结束时间
            log.info("getNewsList总用时：" + (end - begin) + "毫秒。");
            return new ResponseEntity(ResultModel.ok(maps), HttpStatus.OK);
        } catch (Exception e) {
            String errMsg = e.getMessage() == null ? "服务端出错" : e.getMessage();
            log.error(errMsg, e);
            return new ResponseEntity(ResultModel.error(errMsg), HttpStatus.OK);
        }
    }


    @RequestMapping(value = "/searchOrderPubVersionForIndex", method = RequestMethod.GET)
    @ApiOperation(value = "小程序主页公版订单信息")
    public ResponseEntity<ResultModel> searchOrderPubVersionForIndex(@RequestParam String code, @RequestParam String userId, @RequestParam String mobile) {
        List<Order> orderList = null;
        List<WithDrawMoneyMain> withdrawList = null;
        List<Map<String, Object>> maps = Lists.newArrayList();
        Map<String, Object> orderMap = null;
        try {

            //获取最新20订单信息（10条正式订单，10条预受理单）
            orderList = iOrderService.searchOrderPubVersionForIndex(code, userId, mobile);
            if (orderList != null && orderList.size() > 0) {
                for (Order order : orderList) {
                    orderMap = Maps.newHashMap();
                    orderMap.put("tenantCode", order.getTenantCode());
                    orderMap.put("orderNumber", order.getOrderNumber());
                    orderMap.put("withDrawNo", "");
                    orderMap.put("title", order.getReceiver() + "（" + order.getUnloadPlace() + "）");
                    orderMap.put("companyName", order.getTenantName());
                    if (order.getOrderCreateTime() != null) {
                        orderMap.put("date", DateUtil.turnDateToString(order.getOrderCreateTime(), "yyyy-MM-dd"));
                    } else {
                        orderMap.put("date", order.getCreateDate());
                    }
                    orderMap.put("remark", (order.getGenerateFlag() != null && order.getGenerateFlag()) ? "已受理" : "未受理");
                    orderMap.put("generateFlag", (order.getGenerateFlag() != null && order.getGenerateFlag()) ? "1" : "0");
                    orderMap.put("order", order);
                    maps.add(orderMap);
                }
            }

            //获取最新10条取款信息
            withdrawList = withdrawMoneyService.searchWithDrawForIndex(code, mobile);
            if (withdrawList != null && withdrawList.size() > 0) {
                for (WithDrawMoneyMain model : withdrawList) {
                    orderMap = Maps.newHashMap();
                    orderMap.put("tenantCode", model.getCode());
                    orderMap.put("orderNumber", "");
                    orderMap.put("withDrawNo", model.getWithDrawNo());
                    orderMap.put("title", model.getDeliveryCollection() + "元");
                    orderMap.put("companyName", model.getTenantName());
                    orderMap.put("date", model.getCreateDate());
                    orderMap.put("remark", model.getBankCardNo().substring(model.getBankCardNo().length() - 4));
                    orderMap.put("generateFlag", "2");
                    orderMap.put("order", null);
                    maps.add(orderMap);
                }
            }

            //重新排序并得到最新的10条记录
            if (maps.size() > 0) {
                sort(maps);
                if (maps.size() > 10) {
                    maps = maps.subList(0, 10);
                }
            }
            return new ResponseEntity(ResultModel.ok(maps), HttpStatus.OK);
        } catch (Exception e) {
            String errMsg = e.getMessage() == null ? "服务端出错" : e.getMessage();
            log.error(errMsg, e);
            return new ResponseEntity(ResultModel.error(errMsg), HttpStatus.OK);
        }
    }


    private void sort(List<Map<String, Object>> list) {
        Collections.sort(list, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                String date1 = o1.get("date").toString();
                String date2 = o2.get("date").toString();
                return date2.compareTo(date1);
            }
        });
    }

    @RequestMapping(value = "/getOrderInfo", method = RequestMethod.GET)
    @ApiOperation(value = "查询运单详情")
    public ResponseEntity<ResultModel> getOrderInfo(@RequestParam String code, @RequestParam String id, @RequestParam String orderNo, @RequestParam(required = false) String orderBillMasterId) {
        try {
            return new ResponseEntity(ResultModel.ok(iOrderService.getOrderInfo(code, id, orderNo, orderBillMasterId)), HttpStatus.OK);
        } catch (Exception e) {
            log.error("查询运单详情失败", e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "查询运单详情失败"), HttpStatus.OK);
        }
    }

    @RequestMapping(value = "/getPlaceOfLoadingList", method = RequestMethod.GET)
    @ApiOperation(value = "获取开票地点")
    public ResponseEntity<ResultModel> getPlaceOfLoadingList(@RequestParam String code, @RequestParam String longitude, @RequestParam String latitude) {
        try {
            return new ResponseEntity(ResultModel.ok(iOrderService.getPlaceOfLoadingList(code, longitude, latitude)), HttpStatus.OK);
        } catch (Exception e) {
            log.error("获取开票地点失败：" + e.getMessage(), e);
            return new ResponseEntity(ResultModel.error(e.getMessage() != null ? e.getMessage() : "查询认证中心子公司信息出错"), HttpStatus.OK);
        }
    }

    @RequestMapping(value = "/searchOrderListByCode", method = RequestMethod.GET)
    @ApiOperation(value = "查件（BS或者F6）")
    public ResponseEntity<ResultModel> searchOrderListByCode(@RequestParam String data) {
        Map<String, Object> params = null;
        try {
            params = JSON.parseObject(data);
            List<Order> list =iOrderService.getOrderListFromBusinessSys(params);
            if (list!=null&&list.size()>0){
                return new ResponseEntity(ResultModel.ok(), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "查询订单失败"), HttpStatus.OK);
            }

        } catch (JSONException e) {
            log.error("查件失败,参数不对：" + data, e);
            return new ResponseEntity(new ResultModel(101, "参数不对", data), HttpStatus.OK);
        } catch (Exception e) {
            log.error("查件失败,参数：" + data, e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "查询订单失败"), HttpStatus.OK);
        } finally {
            params = null;
        }
    }

    @RequestMapping(value = "/searchGoodsTraceList", method = RequestMethod.GET)
    @ApiOperation(value = "查件（代收平台）")
    public ResponseEntity<ResultModel> searchGoodsTraceList(@RequestParam String data) {
        Map<String, Object> params = null;
        try {
            params = JSON.parseObject(data);
            return new ResponseEntity(ResultModel.ok(iOrderService.getGoodsTraceList(params.get("code").toString(), params.get("mobile").toString(), 0)), HttpStatus.OK);
        } catch (JSONException e) {
            log.error("查件失败,参数不对：" + data, e);
            return new ResponseEntity(new ResultModel(101, "参数不对", data), HttpStatus.OK);
        } catch (Exception e) {
            log.error("查件失败,参数：" + data, e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "查询订单失败"), HttpStatus.OK);
        } finally {
            params = null;
        }
    }

    @RequestMapping(value = "/searchGoodsTraceListNew", method = RequestMethod.GET)
    @ApiOperation(value = "查件（跟踪中心）")
    public ResponseEntity<ResultModel> searchGoodsTraceListNew(@RequestParam String data) {
        Map<String, Object> params = null;
        try {
            params = JSON.parseObject(data);
            String flag=  params.get("flag")+"";
            if (flag==null||flag==""){
                flag="0";
            }
            return new ResponseEntity(ResultModel.ok(iOrderService.getGoodsTraceListNew(params.get("code").toString(), params.get("mobile").toString(), Integer.parseInt(flag))), HttpStatus.OK);
        } catch (JSONException e) {
            log.error("查件失败,参数不对：" + data, e);
            return new ResponseEntity(new ResultModel(101, "参数不对", data), HttpStatus.OK);
        } catch (Exception e) {
            log.error("查件失败,参数：" + data, e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "查询订单失败"), HttpStatus.OK);
        } finally {
            params = null;
        }
    }
    @RequestMapping(value = "/deleteNotRegularOrder", method = RequestMethod.POST)
    @ApiOperation(value = "删除非正式订单")
    public ResponseEntity deleteNotRegularOrder(@RequestParam String data) {
        Order order = null;
        Integer result = 0;
        String errorMessage = "";
        ResultModel resultModel = ResultModel.ok();
        log.info("deleteNotRegularOrder data" + data);
        try {
            if (data != null && data.length() != 0) {
                order = JSON.parseObject(data, Order.class);
                Order oldOrder = iOrderService.selectById(order.getId());
                if (oldOrder == null) {
                    result = 1;
                } else if (oldOrder != null && oldOrder.getGenerateFlag()) {
                    return new ResponseEntity<>(ResultModel.error(ResultStatus.DELETE_ERR, "已转成正式订单，不可以删除"), HttpStatus.OK);
                } else {
                    result = iOrderService.deleteNotRegularById(order);
                }
            } else {
                return new ResponseEntity<>(ResultModel.error(ResultStatus.DELETE_ERR, "参数不能为空"), HttpStatus.OK);
            }

            if (result > 0) {
                return new ResponseEntity<>(resultModel, HttpStatus.OK);
            } else {
                Order oldOrder = iOrderService.selectById(order.getId());
                if (oldOrder != null && oldOrder.getGenerateFlag()) {
                    return new ResponseEntity<>(ResultModel.error(ResultStatus.DELETE_ERR, "已转成正式订单，不可以删除"), HttpStatus.OK);
                } else {
                    return new ResponseEntity<>(resultModel, HttpStatus.OK);
                }
            }
        } catch (Exception e) {
            log.error("删除订单失败", e);
            return new ResponseEntity<>(ResultModel.error(ResultStatus.SERVER_ERROR, "删除订单失败"), HttpStatus.OK);
        }
    }

    @RequestMapping(value = "/batchDeleteOrder", method = RequestMethod.POST)
    @ApiOperation(value = "删除订单")
    @Authorization
    public ResponseEntity batchDeleteOrder(@RequestParam String data) {
        Order order = null;
        Integer result = 0;
        String errorMessage = "";
        String successMesage = "";

        try {
            log.info("batchDeleteOrder data:" + data);
            if (data != null && data.length() != 0) {
                String[] strList = data.split(",");
                for (int i = 0; i < strList.length; i++) {
                    if (strList[i] != null && strList[i].length() != 0) {
                        Order oldOrder = iOrderService.selectByPrimaryKey(Long.parseLong(strList[i]));
                        if (oldOrder != null && oldOrder.getGenerateFlag()) {
                            errorMessage += "id" + strList[i] + "删除失败,已转成正式订单.";
                        } else {
                            successMesage += strList[i] + ",";
                            order = new Order();
                            order.setId(Long.parseLong(strList[i]));
                            result = iOrderService.deleteById(order);
                        }
                    }

                }
            }
        } catch (Exception e) {
            log.error("删除订单失败", e);
        } finally {
            if (errorMessage != null && errorMessage.length() != 0) {
                if (successMesage != null && successMesage.length() != 0) {
                    successMesage = "id" + successMesage + "删除成功";
                    errorMessage = errorMessage + successMesage;
                }
                return new ResponseEntity<>(ResultModel.error(ResultStatus.DELETE_ERR, errorMessage), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(ResultModel.ok(), HttpStatus.OK);
            }

        }

    }

    @RequestMapping(value = "/updateOrder", method = RequestMethod.POST)
    @ApiOperation(value = "修改订单")
    @Authorization
    public ResponseEntity updateOrder(@RequestParam String data) {

        Order order = null;
        Integer result = 0;
        String errorMessage = "";
        try {
            log.info("updateOrder data:" + data);
            long startTime = System.currentTimeMillis();
            if (data != null && data.length() != 0) {
                order = JSON.parseObject(data, Order.class);
                //初始化金额字段（不能为空）

                if (order.getFreight() == null) {
                    order.setFreight(0.0);
                }
                if (order.getCashOnDelivery() == null) {
                    order.setCashOnDelivery(0.0);
                }
                if (order.getCollectionOfMoney() == null) {
                    order.setCollectionOfMoney(0.0);
                }
                if (order.getWeight() == null) {
                    order.setWeight(0.0);
                }
                if (order.getBulk() == null) {
                    order.setBulk(0.0);
                }
                Order oldOrder = iOrderService.selectByPrimaryKey(order.getId());
                if (oldOrder != null && oldOrder.getGenerateFlag()) {
                    errorMessage = "修改失败,已转成正式订单";
                } else {
                    result = iOrderService.updateById(order);
                }
            }
        } catch (Exception e) {
            log.error("修改订单失败", e);
            errorMessage = "修改订单失败" + e.getMessage();
        } finally {
            if (result > 0) {
                ResultModel resultModel = ResultModel.ok();
                return new ResponseEntity<>(resultModel, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(ResultModel.error(ResultStatus.EDIT_ERR, errorMessage), HttpStatus.OK);
            }
        }
    }

    @RequestMapping(value = "/getPlaceOfLoadingDefult", method = RequestMethod.POST)
    @ApiOperation(value = "查询寄件网点默认值")
    @Authorization
    public ResponseEntity<ResultModel> getPlaceOfLoadingDefult(@RequestParam String id,
                                                               @RequestParam(required = false) String code) {
        Map<String, Object> params = null;
        try {
            if (code != null && code.length() != 0) {
                VipAppId v = new VipAppId();
                v.setVipMemberId(Long.parseLong(id));
                v.setCode(code);
                VipAppId vipAppId = iVipService.getVipAppIdById(v);
                return new ResponseEntity(ResultModel.ok(vipAppId), HttpStatus.OK);
            } else {
                return new ResponseEntity(ResultModel.ok(iVipService.getVipById(Long.parseLong(id))), HttpStatus.OK);
            }

        } catch (Exception e) {
            log.error("查询寄件网点默认值,参数：" + id, e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "查询订单失败"), HttpStatus.OK);
        } finally {
            params = null;
        }
    }

    @RequestMapping(value = "/updateUnloadPlaceDefult", method = RequestMethod.POST)
    @ApiOperation(value = "查询寄件网点默认值")
    @Authorization
    public ResponseEntity<ResultModel> updateUnloadPlaceDefult(@RequestParam String id,
                                                               @RequestParam(required = false) String code,
                                                               @RequestParam(required = false) String unloadPlace,
                                                               @RequestParam(required = false) String mobile,
                                                               @RequestParam(required = false) String flag) {
        Map<String, Object> params = null;
        Map<String, Object> obj = Maps.newHashMap();
        try {
            Company company = iCompanyInfoService.getCompanyByCode(code);
            if (company == null || StringUtil.isEmpty(company.getUrl())) {
                throw new NullPointerException("未设置租户信息无法收藏卸货地点");
            }
            String url = company.getUrl() + "/commonlyUseInfo/" + flag + "?accountName=" + company.getF6AccountSet()
                    + "&organizationCode=" + company.getF6OrganizationCode()
                    + "&data={\"userId\": \"" + id + "\",\"mobileTelephone\":\"" + mobile + "\",\"dataType\":\"到货公司\",\"dataValue\":\"" + unloadPlace + "\"}";
            log.info("updateUnloadPlaceDefult:" + url);
            Map<String, Object> res = JSON.parseObject(HttpUtil.get(url));
            try {
                url = company.getUrl() + "/orderBaseInfo?accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode() + "&&userId=" + id;
                //初始化返回值

                Map<String, Object> resu = JSON.parseObject(HttpUtil.get(url));
                if (resu != null && resu.get("content") != null) {
                    obj = JSON.parseObject(resu.get("content").toString());
                }
            } catch (Exception e) {

            }


            return new ResponseEntity(ResultModel.ok(obj), HttpStatus.OK);
        } catch (Exception e) {
            log.error("收藏卸货地点,参数：" + id + "," + code + "," + unloadPlace + "," + mobile, e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "失败"), HttpStatus.OK);
        } finally {
            params = null;
        }
    }

    @RequestMapping(value = "/getSendCompanys", method = RequestMethod.POST)
    @ApiOperation(value = "重新计算网点距离")
    @Authorization
    public ResponseEntity<ResultModel> getSendCompanys(@RequestParam(required = false) String sendCompanyJson,
                                                               @RequestParam(required = false) String longitude,
                                                               @RequestParam(required = false) String latitude) {
        Map<String, Object> params = null;
        Map<String, Object> obj = Maps.newHashMap();
        try {
            JSONArray sendCompanys = JSONArray.parseArray(sendCompanyJson);
            List<Company> f6CompanyList = iCompanyInfoService.getF6WebList(sendCompanys, longitude, latitude);
            return new ResponseEntity(ResultModel.ok(f6CompanyList), HttpStatus.OK);
        } catch (Exception e) {
            log.error("重新计算网点距离,参数：" + sendCompanyJson + "," + sendCompanyJson + "," + longitude + "," + latitude, e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "失败"), HttpStatus.OK);
        } finally{
            params = null;
        }
    }

    @RequestMapping(value = "/getMatchingCompany", method = RequestMethod.POST)
    @ApiOperation(value = "根据收货人坐标获取所在坐标内公司名称")
    @Authorization
    public ResponseEntity<ResultModel> getMatchingCompany(@RequestParam(required = false) String code,
                                                       @RequestParam(required = false) String longitude,
                                                       @RequestParam(required = false) String latitude) {
        Map<String, Object> params = null;
        Map<String, Object> obj = Maps.newHashMap();
        try {
            Company company = iCompanyInfoService.getCompanyByCode(code);
            if (company==null){
                return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, code + "未设置租户信息！"), HttpStatus.OK);
            }
            Map<String,String> header=new HashMap<>();
            String url=company.getUrl() +"/orderBill/getMatchingCompany?databaseId="+company.getF6AccountSet()+"&organizationCode="+company.getF6OrganizationCode();
            Map<String, Object> postParams = Maps.newHashMap();
            postParams.put("longitude",longitude);
            postParams.put("latitude",latitude);
            String  param= "data="+JSONObject.toJSONString(postParams);
            String result = HttpUtils.sendHttp(HttpRequestMethedEnum.HttpPost, url, header, param, 0);
            String companyName="";
            if (StringUtil.isNotEmpty(result)) {
                ResultModel model = JSON.parseObject(result, ResultModel.class);
                if (200 == model.getCode() && "SUCCESS".equals(model.getMsg())) {
                    JSONObject jsonObject =JSONObject.parseObject( model.getContent()+"");
                    if(jsonObject!=null){
                        companyName= jsonObject.get("matchingCompany")+"";
                    }
                }
            }
            return new ResponseEntity(ResultModel.ok(companyName), HttpStatus.OK);
        } catch (Exception e) {
            log.error("根据收货人坐标获取所在坐标内公司名称,参数：" + code + "," + longitude + "," + latitude , e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "失败"), HttpStatus.OK);
        } finally{
            params = null;
        }
    }

    @RequestMapping(value = "/uploadOrder", method = RequestMethod.POST)
    @ApiOperation(value = "保存订单")
    @Authorization
    public ResponseEntity uploadOrder(@RequestParam String data) {
        long startTime = System.currentTimeMillis();
        Order order = null;
        Integer result = 0;
        String resultMesage = "";
        String successId = "";
        String errorId = "";
        try {
            if (data != null && data.length() > 0) {
                String[] ids = data.split(",");
                for (int i = 0; i < ids.length; i++) {
                    if (ids[i] != null && ids[i].length() != 0) {
                        order = iOrderService.selectById(Long.parseLong(ids[i]));
                        if (order != null && "0".equals(order.getUploadFlag())) {
                            try {
                                order.setOrderNumber(String.valueOf(order.getId()));
                                if (order.getOpenId() != null && order.getOpenId().length() != 0) {
                                    order.setUserId(order.getOpenId());
                                }
                                log.info("推送业务系统订单消息开始：" + JSONObject.toJSONString(order));
                                boolean orderResult = sendMessageToBusiness(order);
                                log.info("推送业务系统订单消息结束：" + orderResult);


                                //同步业务系统数据
                                long start = System.currentTimeMillis();
                                log.info("补传开始：" + start);
                                String r = syncPreOrder(order, "add");
                                if ("SUCCESS".equals(r)) {
                                    successId += order.getId() + ",";
                                } else {
                                    errorId += order.getId() + ",";
                                }
                                log.info("补传结束：用时" + (System.currentTimeMillis() - start));
                            } catch (Exception e) {
                                resultMesage = "上传失败：" + e.getMessage() + ".";
                            }

                        }
                    }
                }
            }


        } catch (Exception e) {
            log.error("订单上传失败", e);
            resultMesage = "补传异常" + e.getMessage() + ".";
        } finally {
            if (successId != null && successId.length() != 0) {
                resultMesage = resultMesage + " id:" + successId + "补传成功.";
            }
            if (errorId != null && errorId.length() != 0) {
                resultMesage = resultMesage + " id:" + errorId + "补传失败.";
            }
            return new ResponseEntity(ResultModel.ok(resultMesage), HttpStatus.OK);
        }
    }

    @RequestMapping(value = "/searchOrderNumberList", method = RequestMethod.GET)
    @ApiOperation(value = "F6查询运货单数据")
    public ResponseEntity<ResultModel> searchOrderNumberList(@RequestParam String data) {
        Map<String, Object> params = null;
        try {
            params = JSON.parseObject(data);
            ResultModel result = iOrderService.searchOrderNumberList(params);
            return new ResponseEntity(result, HttpStatus.OK);
        } catch (Exception e) {
            log.error("查询货运单执行异常：" + data, e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "查询货运单失败"), HttpStatus.OK);
        } finally {
            params = null;
        }
    }

}
